package com.chb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chb.entity.Order;
import com.chb.entity.PayLog;
import com.chb.mapper.OrderMapper;
import com.chb.mapper.PayLogMapper;
import com.chb.service.OrderService;
import com.chb.utils.HttpClient;
import com.chb.vo.Result;
import com.github.wxpay.sdk.WXPayUtil;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 陈海彬
 * @description 针对表【t_order(订单)】的数据库操作Service实现
 * @createDate 2023-12-02 19:16:41
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private PayLogMapper payLogMapper;

    @Value("${weixin.appid}")
    private String appId;

    @Value("${weixin.mch_id}")
    private String mchId;

    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result createNavite(String orderNo) {
        // 1.根据订单号查询出订单信息
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        wrapper.eq(Order::getStatus, 0);
        Order order = this.orderMapper.selectOne(wrapper);
        if (order != null) {
            // 设置请求的参数————格式为xml格式
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);   // 公众号
            params.put("mch_id", mchId);  // 商户号
            params.put("nonce_str", WXPayUtil.generateNonceStr());      // 32位随机字符串
            params.put("body", order.getCourseTitle());                 // 商品描述
            params.put("out_trade_no", orderNo);                        // 商户订单号
            // params.put("total_fee", new BigDecimal(order.getTotalFee().multiply(new BigDecimal(100)).longValue()) + "");
            params.put("total_fee", "1");
            params.put("spbill_create_ip", "127.0.0.1");    // 未来写成项目部署的ip
            params.put("notify_url", "http://localhost:9000/pay/back");  // 回调地址
            params.put("trade_type", "NATIVE");                          // 交易类型

            System.out.println(params);
            try {
                // 2.创建HttpClient对象 作为远程调用
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                // 支持http协议
                client.setHttps(true);
                client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                // 发送请求
                client.post();

                // 获得响应对象
                String content = client.getContent();

                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if ("SUCCESS".equals(map.get("result_code"))) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("codeUrl", map.get("code_url"));
                    result.put("price", order.getTotalFee());
                    result.put("orderNo", orderNo);
                    return new Result(200, "生成二维码成功", result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new Result(500, "订单失效", null);
    }

    @Override
    public Result queryPayStatus(String orderNo) {
        try {
            // 1.根据订单状态查询微信的支付情况
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);             // 服务商的APPID
            params.put("mch_id", mchId);            // 商户号
            params.put("out_trade_no", orderNo);    // 商户订单号
            params.put("nonce_str", WXPayUtil.generateNonceStr());  //  随机字符串

            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
            client.post();

            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if ("SUCCESS".equals(map.get("trade_state"))) {
                // 1.修改订单状态
                LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(Order::getStatus, 1)
                        .set(Order::getGmtModified, new Date())
                        .eq(Order::getOrderNo, orderNo)
                        .eq(Order::getStatus, 0);
                orderMapper.update(updateWrapper);

                // 2.在支付记录表中添加支付记录
                PayLog payLog = new PayLog();
                payLog.setOrderNo(orderNo);         // 订单号
                // 订单支付时间
                payLog.setPayTime(
                        new SimpleDateFormat("yyyyMMddHHmmss").parse(map.get("time_end"))
                );
                payLog.setTotalFee(new BigDecimal(map.get("total_fee")));   // 支付金额(分)
                payLog.setTransactionId(map.get("transaction_id"));         // 交易流水号
                payLog.setTradeState(map.get("trade_state"));               // 交易状态
                payLog.setPayType(0);               // 支付类型(0:微信，1：支付宝)
                payLog.setIsDeleted(0);             // 逻辑删除(0:未删除)
                payLog.setGmtCreate(new Date());    // 创建时间
                payLog.setGmtModified(new Date());  // 更新时间
                this.payLogMapper.insert(payLog);

                return new Result(200, "支付成功", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(500, "支付失败", null);
    }
}




